package com.example.casper.Experiment2024.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.example.casper.Experiment2024.R;
import com.example.casper.Experiment2024.activity.BookDetailsActivity;
import com.example.casper.Experiment2024.adapter.RecyclerViewBookAdapter;
import com.example.casper.Experiment2024.data.Book;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class BookListFragment extends Fragment {
    // RecyclerView控件和书籍数据列表
    private RecyclerView recyclerView;
    private List<Book> books;
    private RecyclerViewBookAdapter adapter;

    // ActivityResultLauncher，用于启动添加和更新书籍的Activity
    private ActivityResultLauncher<Intent> addItemLauncher;
    private ActivityResultLauncher<Intent> updateItemLauncher;

    // 当前选中的书籍位置
    private int position = 0;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 初始化视图
        View view = inflater.inflate(R.layout.fragment_book_list, container, false);

        recyclerView = view.findViewById(R.id.recycler_view_the_books); // 获取RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // 设置布局管理器

        // 获取书籍列表并设置适配器
        books = getListBooks();
        adapter = new RecyclerViewBookAdapter(books);
        recyclerView.setAdapter(adapter);

        registerForContextMenu(recyclerView); // 注册上下文菜单

        // 注册用于处理添加书籍的ActivityResultLauncher
        addItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == getActivity().RESULT_OK) {
                        // 获取返回的数据并添加新书籍
                        Intent data = result.getData();
                        String name = data.getStringExtra("name");
                        String priceStr = data.getStringExtra("price");
                        Double price = priceStr.isEmpty() ? 0.0 : Double.valueOf(priceStr);
                        books.add(position + 1, new Book(name, price, R.drawable.book_no_name)); // 添加新书籍
                        adapter.notifyItemInserted(position + 1); // 更新RecyclerView
                        saveBooks(); // 保存书籍列表
                    }
                }
        );

        // 注册用于处理更新书籍的ActivityResultLauncher
        updateItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == getActivity().RESULT_OK) {
                        // 获取返回的数据并更新选中的书籍
                        Intent data = result.getData();
                        String name = data.getStringExtra("name");
                        String priceStr = data.getStringExtra("price");
                        Double price = priceStr.isEmpty() ? 0.0 : Double.valueOf(priceStr);
                        Book book = books.get(position);
                        book.setTitle(name); // 更新书名
                        book.setPrice(price); // 更新书籍价格
                        adapter.notifyItemChanged(position); // 更新RecyclerView
                        saveBooks(); // 保存书籍列表
                    }
                }
        );

        return view;
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        position = item.getGroupId(); // 获取当前选中的书籍位置
        switch (item.getItemId()) {
            case 1: // 添加
                // 启动书籍详情Activity，进行添加操作
                Intent intent = new Intent(getActivity(), BookDetailsActivity.class);
                addItemLauncher.launch(intent);
                break;
            case 2: // 修改
                // 启动书籍详情Activity，进行更新操作
                Intent intentUpdate = new Intent(getActivity(), BookDetailsActivity.class);
                Book book = books.get(position);
                intentUpdate.putExtra("name", book.getTitle()); // 传递书名
                intentUpdate.putExtra("price", String.valueOf(book.getPrice())); // 传递价格
                updateItemLauncher.launch(intentUpdate);
                break;
            case 3: // 删除
                confirmDelete(); // 显示删除确认对话框
                break;
            default:
                super.onContextItemSelected(item);
        }
        return false;
    }

    // 显示删除确认对话框
    private void confirmDelete() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("确认");
        builder.setMessage("您是否确定删除这本书");
        builder.setPositiveButton("是", (dialog, which) -> {
            books.remove(position); // 删除选中的书籍
            adapter.notifyItemRemoved(position); // 更新RecyclerView
            saveBooks(); // 保存修改后的书籍列表
        });
        builder.setNegativeButton("否", null); // 取消删除
        builder.create().show(); // 显示对话框
    }

    // 保存书籍列表到文件
    private void saveBooks() {
        try (ObjectOutputStream oos = new ObjectOutputStream(requireActivity().openFileOutput("books.dat", Context.MODE_PRIVATE))) {
            oos.writeObject(books); // 将书籍列表保存到文件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从文件加载书籍列表
    private List<Book> getListBooks() {
        List<Book> books = new ArrayList<>();
        boolean haveData;
        try (ObjectInputStream ois = new ObjectInputStream(requireActivity().openFileInput("books.dat"))) {
            books = (List<Book>) ois.readObject(); // 读取书籍列表
            haveData = !books.isEmpty(); // 检查文件是否包含书籍数据
        } catch (FileNotFoundException e) {
            haveData = false; // 文件未找到
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            haveData = false; // 加载数据失败
        }

        // 如果没有数据，则添加一些默认书籍
        if (!haveData) {
            books.add(new Book("创新工程实践", 8.8, R.drawable.book_no_name));
            books.add(new Book("软件项目管理案例教程（第3版）", 88.8, R.drawable.book_2));
            books.add(new Book("信息安全数学基础（第2版）", 666.0, R.drawable.book_1));
        }
        return books; // 返回书籍列表
    }
}
